document.addEventListener('DOMContentLoaded', () => {
    initQuiz();
});

const questionContainer = document.getElementById('question');
const optionsContainer = document.getElementById('options');
const progressContainer = document.getElementById('progress');
const resultContainer = document.getElementById('result');

let currentQuestionIndex = 0;
let score = 0;
let selectedQuestions = [];

function initQuiz() {
    // 打乱题库并选择指定数量的题目
    const shuffledQuestions = shuffleArray([...questionBank]);
    selectedQuestions = shuffledQuestions.slice(0, config.totalQuestions);
    currentQuestionIndex = 0;
    score = 0;
    showQuestion();
}

function shuffleArray(array) {
    return array.sort(() => Math.random() - 0.5);
}

function showQuestion() {
    const currentQ = selectedQuestions[currentQuestionIndex];
    questionContainer.textContent = currentQ.question;
    progressContainer.textContent = `题目 ${currentQuestionIndex + 1}/${selectedQuestions.length}`;
    
    // 清空并创建新选项
    optionsContainer.innerHTML = '';
    const shuffledOptions = shuffleArray([...currentQ.options]);
    
    shuffledOptions.forEach(option => {
        const button = document.createElement('button');
        button.textContent = option;
        button.addEventListener('click', () => handleAnswer(option, currentQ.correctAnswer));
        optionsContainer.appendChild(button);
    });
}

function handleAnswer(selectedAnswer, correctAnswer) {
    const buttons = optionsContainer.querySelectorAll('button');
    
    buttons.forEach(button => {
        button.disabled = true;
        if (button.textContent === correctAnswer) {
            button.classList.add('correct');
        }
        if (button.textContent === selectedAnswer && selectedAnswer !== correctAnswer) {
            button.classList.add('incorrect');
        }
    });

    if (selectedAnswer === correctAnswer) score++;

    currentQuestionIndex++;
    setTimeout(() => {
        if (currentQuestionIndex < selectedQuestions.length) {
            showQuestion();
        } else {
            showFinalResult();
        }
    }, 1500);
}

function showFinalResult() {
    questionContainer.textContent = '';
    optionsContainer.innerHTML = '';
    progressContainer.textContent = '';
    
    const accuracy = (score / selectedQuestions.length * 100).toFixed(1);
    resultContainer.innerHTML = `
        <h3>答题完成！</h3>
        <p>正确题数：${score}/${selectedQuestions.length}</p>
        <p>正确率：${accuracy}%</p>
        <p>${accuracy >= 80 ? '🎉 优秀！' : accuracy >= 60 ? '👍 继续努力！' : '💪 再加把劲！'}</p>
    `;
}
